package com.tong.filter;

import com.tong.RedisService;
import com.tong.pojo.Books;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.logging.LogRecord;

public class LoginFilter implements HandlerInterceptor {

    @Autowired
    private RedisService redisService;

    //在业务处理器处理请求之前被调用，可以进行登录拦截，编码处理、安全控制、权限校验等处理；
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        for(Cookie cookie : cookies){
            String name = cookie.getName();
            String value = cookie.getValue();
            if(name.equals("right")){
                return true;
            }
        }
        response.sendRedirect(request.getContextPath()+"/loginPage");
        return false;
    }

    //在业务处理器处理请求执行完成后，生成视图之前被调用。即调用了Service并返回ModelAndView，但未进行页面渲染，可以修改ModelAndView，这个比较少用。
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        Long count = redisService.bitcount("count");
        System.out.println("网站访问量:"+count);
    }

    //在DispatcherServlet完全处理完请求后被调用，可用于清理资源等。已经渲染了页面。
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}